package com.googlecode.moneyManager.spreadSheetReader.model;

import com.google.gdata.client.spreadsheet.CellQuery;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.*;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import com.googlecode.moneyManager.exceptions.DataAccessException;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

/**
 * Author: Sergiy Doroshenko
 * Date: Jul 21, 2010
 * Time: 1:50:20 PM
 */
public class SpreadsheetGoogleDocument {
    private String user;
    private String password;
    private SpreadsheetService service;
    private List<CellEntry> cellEntries;

    public SpreadsheetGoogleDocument(String user, String password) {
        this.user = user;
        this.password = password;
    }

    public List<CellEntry>  getStaticGarbageCellEntries(){
         if(cellEntries == null){
             cellEntries = loadGarbageCellEntries();
         }
        return cellEntries;
    }

    private List<CellEntry> loadGarbageCellEntries() {
        try {
            URL cellFeedUrl = getWorksheetEntry("garbage", 0).getCellFeedUrl();
            CellQuery query = new CellQuery(cellFeedUrl);
            query.setMinimumRow(1);
            query.setMaximumRow(6);
            query.setMinimumCol(8);
            query.setMaximumCol(10);
            CellFeed cellFeed = service.query(query, CellFeed.class);
            return cellFeed.getEntries();
        } catch (Throwable t) {
            throw new DataAccessException(" can't load data from garbage spreadsheet ", t);
        }
    }

    private List<SpreadsheetEntry> loadService() throws AuthenticationException, MalformedURLException, ServiceException, IOException {
        service = new SpreadsheetService("garbage");

        service.setUserCredentials(user, password);

        URL metafeedUrl = null;

        metafeedUrl = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");

        SpreadsheetFeed feed = null;

        feed = service.getFeed(metafeedUrl, SpreadsheetFeed.class);

        return feed.getEntries();
    }

    private WorksheetEntry getWorksheetEntry(String spreadsheetEntryName, Integer worksheetEntryNumber) throws AuthenticationException, MalformedURLException, ServiceException, IOException {
        List<SpreadsheetEntry> spreadsheets = loadService();
        for (int i = 0; i < spreadsheets.size(); i++) {
            SpreadsheetEntry entry = spreadsheets.get(i);
            if (entry.getTitle().getPlainText().equals(spreadsheetEntryName)) {
                List<WorksheetEntry> worksheets = entry.getWorksheets();
                return worksheets.get(worksheetEntryNumber);
            }
        }
        return null;
    }
}
